//
//  SSSSShopController.m
//  Ghac 4S
//
//  Created by apple apple on 11-12-28.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//
#import "Global.h"
#import "SSSSShopController.h"
#import "DataFactory.h"
#import "KXML.h"
#import "KXMLNode.h"
#import "KXPath.h"
#import "pinyin.h"
#import "MyProvinceCell.h"
#import "MyShopCell.h"
#import "MySearchBarController.h"
@interface SSSSShopController(private)
-(void) setUpProvinceListFromXML:(KXML*)xml;
-(void) setUpCityListFromXML:(KXML*)xml withProvince:(NSString*)province;
-(void) setUpShopListFromXML:(KXML*)xml withCity:(NSString*)city;
-(void) animateTheViews:(UIView*)viewGone targetView:(UIView*)viewCome;
-(NSString*) stringWithDetailMsgOfShop:(KXMLNode*)shopNode;
-(void) searchBarReturn:(NSNotification*)sender;
-(void) animateEnds:(id)sender;
@end

@implementation SSSSShopController
@synthesize provinceView;
@synthesize cityView;
@synthesize innerViewContainer;
@synthesize provinceTableView;
@synthesize cityTableView;
@synthesize shopTableView;
@synthesize shopView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) 
    {
        // Custom initialization
        [self setTitle:@"location"];
        m_lastSelectedIndexPath = [[NSIndexPath indexPathForRow:-1 inSection:0] retain];
    }
    return self;
}
-(void)dealloc
{
    [self viewDidUnload];
    KRELEASE(m_provinceInSort);
    KRELEASE(m_provinceFirstLetterList);
    KRELEASE(m_xml);
    KRELEASE(m_cityList);
    KRELEASE(m_shopList);
    KRELEASE(m_lastSelectedIndexPath);
    [super dealloc];
}
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}



/** 
 * return the shops detail msg in string format
 */
-(NSString *)stringWithDetailMsgOfShop:(KXMLNode *)shopNode
{
    NSMutableString* str = [NSMutableString string];
    [str appendFormat:@"%@\n", [shopNode valueForKeyPath:@"name.__nodeValue__"]];
    [str appendFormat:@"地址:%@\n", [shopNode valueForKeyPath:@"address.__nodeValue__"]];
    [str appendFormat:@"咨询电话:%@\n", [shopNode valueForKeyPath:@"phone.__nodeValue__"]];
    [str appendFormat:@"24小时求援电话:%@", [shopNode valueForKeyPath:@"emergencyNum.__nodeValue__"]];
    return str;
}


/**
 * init the provinceLetterList and provinceList from the xml
 *
 */
-(void)setUpProvinceListFromXML:(KXML *)xml
{
    KRELEASE(m_provinceInSort);
    KRELEASE(m_provinceFirstLetterList);
    m_provinceInSort = [[NSMutableDictionary alloc] init];
    m_provinceFirstLetterList = [[NSMutableArray alloc] init ];
    
    KXPath* path = [[KXPath alloc] initWithString:@"shop" predicate:Nil];
    NSArray* list = [xml arrayByXPath:path];
    [path release];
    for(KXMLNode* node in list)
    {
        NSString* provinceName = [node valueForKeyPath:@"province.__nodeValue__"];
        char charAtFirst = pinyinFirstLetter([provinceName characterAtIndex:0]);
        NSString* charStr = [[NSString stringWithFormat:@"%c", charAtFirst] uppercaseString];
        
        NSMutableArray* provinceList = [m_provinceInSort objectForKey:charStr];
        if (![m_provinceFirstLetterList containsObject:charStr])
        {
            [m_provinceFirstLetterList addObject:charStr];
        }
        
        if (provinceList == nil)
        {
            provinceList = [[[NSMutableArray alloc] init ] autorelease];
            [m_provinceInSort setValue:provinceList forKey:charStr];
        }
        
        if (![provinceList containsObject:provinceName])
        {
            [provinceList addObject:provinceName];
        }
        [provinceList simpleSort:YES];
        [m_provinceInSort setValue:provinceList forKey:charStr];
        
    }
    [m_provinceFirstLetterList simpleSort:YES];
}

/**
 * set up the list of city with each selection of province;
 *
 *
 */
-(void)setUpCityListFromXML:(KXML *)xml withProvince:(NSString *)province
{
    KRELEASE(m_cityList);
    m_cityList = [[NSMutableArray alloc] init ];
    NSString*  predicateWord = [NSString stringWithFormat:@"province == '%@'", province];
    KXPath* path = [[KXPath alloc] initWithString:@"shop" predicate:predicateWord];
    NSArray* list = [xml arrayByXPath:path];
    
    for (KXMLNode* node in list)
    {
        NSString* cityName = [node valueForKeyPath:@"city.__nodeValue__"];
        if (![m_cityList containsObject:cityName])
        {
            [m_cityList addObject:cityName];
        }
    }
    [m_cityList simpleSort:YES];
}
-(void)setUpShopListFromXML:(KXML *)xml withCity:(NSString *)city
{
    KRELEASE(m_shopList);
    NSString* predicateWord = [NSString stringWithFormat:@"city == '%@'", city];
    KXPath* path = [[KXPath alloc] initWithString:@"shop" predicate:predicateWord];
    NSArray* list = [xml arrayByXPath:path];
    m_shopList = [[NSMutableArray arrayWithArray:list] retain];
}
/**
 * to animate the views, switch
 *
 *
 */
-(void)animateTheViews:(UIView *)viewGone targetView:(UIView *)viewCome
{
    m_currentInnerView = viewCome;
    [self.innerViewContainer addSubview:viewCome];
    [viewGone setFrame:CGRectMake(0, 0, viewGone.frame.size.width, viewGone.frame.size.height)];
    [viewCome setFrame:CGRectMake(0, 0, viewCome.frame.size.width, viewCome.frame.size.height)];
    [viewCome setFrame:CGRectOffset(viewCome.frame, viewCome.frame.size.width, 0)];
    [UIView beginAnimations:@"innerViewAnimation" context:nil];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animateEnds:)];
    [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self.innerViewContainer cache:YES];
    [viewCome setFrame:CGRectMake(0, 0, viewCome.frame.size.width, viewCome.frame.size.height)];
    [viewGone setFrame:CGRectOffset(viewGone.frame, -viewGone.frame.size.width, 0)];
    [UIView commitAnimations];
}
-(void)animateEnds:(id)sender
{
//    while (self.innerViewContainer.subviews.count > 1)
//    {
//        UIView* firstView = [self.innerViewContainer.subviews objectAtIndex:0];
//        if(firstView != m_currentInnerView)
//        {
//            [firstView removeFromSuperview];
//        }
//        else
//        {
//            [self.innerViewContainer exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
//        }
//    }
    
}

#pragma mark - View lifecycle

-(void)backBtnClick:(id)sender
{
    if (m_currentInnerView == self.provinceView)
    {
        [[Global mainRootController] backToEntryView];
    }
    else
    {
        [self animateTheViews:m_currentInnerView targetView:self.provinceView];
        [self.provinceTableView reloadData];
    }
}

/**
 * 数据加载完成
 *
 */
-(void)onData:(id)sender
{
    KRELEASE(m_xml);
    m_xml = [[KXML alloc] initWithData:sender];
    [self setUpProvinceListFromXML:m_xml];
    [self.innerViewContainer addSubview:self.provinceView];
    m_currentInnerView = self.provinceView;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.provinceTableView)
    {
        return m_provinceFirstLetterList.count ; 
    }
    else
    {
        return 1;
    }
    
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.provinceTableView)
    {
        return [m_provinceFirstLetterList objectAtIndex:section];
    }
    else
    {
        return nil;
    }
    
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView == self.provinceTableView)
    {
        return m_provinceFirstLetterList;
    }
    else
    {
        return nil;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.provinceTableView)
    {
        NSArray* list = [m_provinceInSort objectForKey:[m_provinceFirstLetterList objectAtIndex:indexPath.section]];
        NSString* label = [list objectAtIndex:indexPath.row];
        
        [self animateTheViews:self.provinceView targetView:self.cityView];
        
        [self setUpCityListFromXML:m_xml withProvince:label];
        [self.cityTableView reloadData];
    }
    else if (tableView == self.cityTableView)
    {
        NSString* label = [m_cityList objectAtIndex:indexPath.row];
        [self animateTheViews:self.cityView targetView:self.shopView];
        [self setUpShopListFromXML:m_xml withCity:label];
        KRELEASE(m_lastSelectedIndexPath);
        m_lastSelectedIndexPath = [[NSIndexPath indexPathForRow:-1 inSection:0] retain];
        [self.shopTableView reloadData];
        
    }
    else
    {
        NSIndexPath* oldIndexPath = (m_lastSelectedIndexPath.row == -1 || m_lastSelectedIndexPath.row == indexPath.row) ? nil : m_lastSelectedIndexPath;
        m_lastSelectedIndexPath = [indexPath retain];
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, oldIndexPath, nil] withRowAnimation:UITableViewRowAnimationLeft];
        KRELEASE(oldIndexPath);
    }
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.provinceTableView)
    {
        NSArray* list = [m_provinceInSort objectForKey:[m_provinceFirstLetterList objectAtIndex:section]];
        return list.count;
    }
    else if (tableView == self.cityTableView)
    {
        return m_cityList.count;
    }
    else
    {
        return m_shopList.count;
    }
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //err....not so good....
    MyProvinceCell* cell = (MyProvinceCell*)[tableView dequeueReusableCellWithIdentifier:@"demo"];
    if (cell == nil)
    {
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"MyProvinceCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    if (tableView == self.provinceTableView)
    {
        NSArray* list = [m_provinceInSort objectForKey:[m_provinceFirstLetterList objectAtIndex:indexPath.section]];
        NSString* label = [list objectAtIndex:indexPath.row];
        [cell.textLabel setText:label];
    }
    else if (tableView == self.cityTableView)
    {
        NSString* label = [m_cityList objectAtIndex:indexPath.row];
        [cell.textLabel setText:label];
    }
    else
    {
        MyShopCell* shopCell = (MyShopCell*)[tableView dequeueReusableCellWithIdentifier:@"demo"];
        if (shopCell == nil)
        {
            NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"MyShopCell" owner:self options:nil];
            shopCell = [nib objectAtIndex:0];
        }
        [shopCell.detailView setHidden:YES];
        KXMLNode* shopNode = [m_shopList objectAtIndex:indexPath.row];
        NSString* label = [shopNode valueForKeyPath:@"name.__nodeValue__"];
        [shopCell.titleLabel setText:label];
        [shopCell.detailTextView setText:[self stringWithDetailMsgOfShop:shopNode]];
        if (m_lastSelectedIndexPath.row == indexPath.row)
        {
            [shopCell.detailView setHidden:NO];
            [shopCell.titleView setHidden:YES];
        }
        else
        {
            [shopCell.detailView setHidden:YES];
            [shopCell.titleView setHidden:NO];
        }
        return shopCell;
        
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.shopTableView)
    {
        if (m_lastSelectedIndexPath.row  == indexPath.row)
        {
            return 150;
        }
    }
    return tableView.rowHeight;

}
-(void)searchBarReturn:(NSNotification *)sender
{
    UITextField* textfield = (UITextField*)[sender object];
    NSString* text = [textfield.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* predictwords;
    if(text.length == 0)
    {
        predictwords = nil;//[NSString stringWithFormat:@""];
    }
    else
    {
        predictwords = [NSString stringWithFormat:@"name LIKE[cd] '*%@*'", text];
    }
    KXPath* path = [[KXPath alloc] initWithString:@"shop" predicate:predictwords];
    KRELEASE(m_shopList);
    m_shopList = [[m_xml arrayByXPath:path] retain];
    if (m_currentInnerView != self.shopView)
    {
        [self animateTheViews:m_currentInnerView targetView:self.shopView];
    }
    [self.shopTableView reloadData];

    
    [path release];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    DataFactory* datafactory = [DataFactory sharedDataFactory];
    id dataProvide = [datafactory produceProviderWithDelegate:self];
    if (dataProvide == Nil)
    {
        NSLog(@"error1");
        return;
    }
    
    MySearchBarController* searchBarController = [[MySearchBarController alloc] init];
    CGRect mainframe = self.view.frame;
    CGRect barframe = searchBarController.view.frame;
    barframe.origin.y = mainframe.size.height - barframe.size.height;
    [searchBarController setViewFrame:barframe];
    [self.view addSubview:searchBarController.view];
    //    searchBarController.targetView = searchBarController.view;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchBarReturn:) name:UITextFieldTextDidEndEditingNotification object:searchBarController.textfield];
    m_searchBarController = searchBarController;
    
    [datafactory askDatas:self.title];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.innerViewContainer = nil;
    self.provinceView = nil;
    self.provinceTableView = nil;
    self.cityTableView = nil;
    self.shopTableView = nil;
    self.shopView = nil;
    self.cityView = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidEndEditingNotification object:m_searchBarController.textfield];
    KRELEASE(m_searchBarController);
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
